package org.nf.vrs.authenticateservice.service;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.nf.vrs.authenticate.exception.AuthenticateException;
import org.nf.vrs.authenticate.inf.UserTokenService;
import org.nf.vrs.authenticateservice.util.JwtUtils;
import org.nf.vrs.userservice.inf.UserService;

import java.util.Map;

/**
 * @author duang
 * @date 2022/3/30
 */
@Slf4j
@DubboService(interfaceClass = UserTokenService.class, version = "1.0.0")
public class UserTokenServiceImpl implements UserTokenService {
    /**
     * 创建token
     * @param payload
     * @param ttl
     * @return
     */
    @Override
    public String create(Map<String, Object> payload, long ttl) {
        return JwtUtils.createToken(payload,ttl);
    }

    /**
     * 检查token是否有效
     * @param token
     */
    @Override
    public void verify(String token) {
        try {
            JwtUtils.verify(token);
        } catch (SecurityException e) {
            throw new AuthenticateException("Invalid JWT signature.");
        } catch (MalformedJwtException e) {
            throw new AuthenticateException("Invalid JWT token.");
        } catch (ExpiredJwtException e) {
            throw new AuthenticateException("Expired JWT token.");
        } catch (UnsupportedJwtException e) {
            throw new AuthenticateException("Unsupported JWT.");
        } catch (IllegalArgumentException e) {
            throw new AuthenticateException("JWT token compact of handler are invalid.");
        }
    }

    /**
     * 获取载体内容
     * @param token
     * @param name
     * @param type
     * @param <T>
     * @return
     */
    @Override
    public <T> T getPayload(String token, String name, Class<T> type) {
        return JwtUtils.getPayload(token, name, type);
    }
}